package com.ogawa.joypal.user.activity

import android.os.Build
import android.text.Editable
import android.text.TextWatcher
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.ToastUtils
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener
import com.ogawa.base.adapter.GridImageAdapter
import com.ogawa.base.base.BaseVMActivity
import com.ogawa.base.utils.AppUtil
import com.ogawa.projectcommon.constants.UrlPathConstant
import com.ogawa.joypal.user.R
import kotlinx.android.synthetic.main.activity_user_suggest.*
import com.ogawa.base.utils.GlideEngine
import com.ogawa.base.utils.ToastUtil
import com.ogawa.base.utils.isEmptyStr
import com.ogawa.joypal.user.viewmodel.LoginSuggestViewModel
import com.ogawa.projectcommon.constants.Constant


@Route(path = UrlPathConstant.ACTIVITY_USER_SUGGEST)
public class UserSuggestActivity : BaseVMActivity<LoginSuggestViewModel>() {
    override fun getLayoutId(): Int {
        return R.layout.activity_user_suggest
    }
    private var curChooseImageIndex = 0
    private var mGridImageAdapter  = GridImageAdapter()
    override fun providerVMClass(): Class<LoginSuggestViewModel>? {
        return LoginSuggestViewModel::class.java
    }

    override fun observeVM() {
        mViewModel.state.observe(this, Observer {
            if (it ==  Constant.SUCCESS){
                ToastUtil.showToast(getString(R.string.success), Toast.LENGTH_SHORT)
                finish()
            }
        })
    }

    override fun initView() {
        super.initView()
        setTitle(getString(R.string.user_suggest))
        suggestContentEt.addTextChangedListener(object :TextWatcher{
            override fun afterTextChanged(p0: Editable?) {
                numberCountTv.text = "${p0!!.length}/200"
            }
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
        })

        mGridImageAdapter = GridImageAdapter(R.layout.gv_filter_image, ArrayList())
        mGridImageAdapter.MaxNumber = 4
        mGridImageAdapter.data.add(GridImageAdapter.GridImageBean("", false))
        mGridImageAdapter.setmGridImageAdapterListener(object : GridImageAdapter.GridImageAdapterListener{
            override fun onclickItem(position: Int) {
                curChooseImageIndex = position
                // 进入相册 以下是例子：不需要的api可以不写
                PictureSelector.create(this@UserSuggestActivity)
                    .openGallery(PictureMimeType.ofImage()) // 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .imageEngine(GlideEngine.createGlideEngine())
                    .maxSelectNum(1) // 最大图片选择数量
                    .minSelectNum(1) // 最小选择数量
                    .imageSpanCount(4) // 每行显示个数
                    .selectionMode(PictureConfig.SINGLE) // 多选 or 单选
                    .previewImage(true) // 是否可预览图片
                    .isCamera(true) // 是否显示拍照按钮
                    .isZoomAnim(true) // 图片列表点击 缩放效果 默认true
                    .enableCrop(true) // 是否裁剪
                    .compress(true) // 是否压缩
                    .synOrAsy(true) //同步true或异步false 压缩 默认同步
                    .glideOverride(160, 160) // glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                    .freeStyleCropEnabled(true) // 裁剪框是否可拖拽
                    .minimumCompressSize(100) // 小于100kb的图片不压缩
//                .forResult(PictureConfig.CHOOSE_REQUEST) //结果回调onActivityResult code
                    .forResult(object : OnResultCallbackListener<LocalMedia> {
                        override fun onResult(selectList: MutableList<LocalMedia>?) {
                            try {
                                var path = selectList!![0].compressPath
                                if (path==null || path.isEmpty()){
                                    if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.P){
                                        path = selectList!![0].androidQToPath
                                    }else{
                                        path = selectList!![0].realPath
                                    }
                                }
                                if (path==null || path.isEmpty()){
                                    ToastUtils.showShort(getString(R.string.fail_read_image))
                                    return
                                }

//                                com.blankj.utilcode.util.LogUtils.e("当前选择的 compressPath：${FileUtils.getSize(path)}")
//                                com.blankj.utilcode.util.LogUtils.e("当前选择的 path：${FileUtils.getSize(selectList!![0].path)}")
                                com.blankj.utilcode.util.LogUtils.e("当前选择的：${path}")
                                val item = mGridImageAdapter.getItem(curChooseImageIndex)
                                item!!.path = path
                                item!!.isLocalFile = true
                                if (curChooseImageIndex == mGridImageAdapter.data.size-1 &&
                                    mGridImageAdapter.data.size < mGridImageAdapter.MaxNumber){
                                    mGridImageAdapter.addData(GridImageAdapter.GridImageBean("",false))
                                }
                                mGridImageAdapter.notifyItemChanged(curChooseImageIndex)
                            }catch (e:Exception){
                                e.printStackTrace()
                            }
                            getImageCount()
                        }

                        override fun onCancel() {
                            getImageCount()
                        }

                    })
            }

            override fun removeItem(position: Int) {
                getImageCount()
            }
        })

        val manager = GridLayoutManager(mActivity, 4, GridLayoutManager.VERTICAL, false)
        imgSelectRv.layoutManager = manager
        imgSelectRv.setHasFixedSize(true)
        imgSelectRv.adapter = mGridImageAdapter

        btn_commit.setOnClickListener {
            var contentStr = suggestContentEt.text.toString()
            if (isEmptyStr(contentStr)){
                ToastUtils.showShort(getString(R.string.place_input_suggest))
                return@setOnClickListener
            }
            if (contentStr.length < 10){
                ToastUtils.showShort(getString(R.string.place_input_suggest))
                return@setOnClickListener
            }
            mViewModel.mUserFeedBacksRequest.content =contentStr
            mViewModel.mUserFeedBacksRequest.type = "1"
            mViewModel.mUserFeedBacksRequest.phone = telEt.text.toString()
            try{
                mGridImageAdapter.data[0]?.run {
                mViewModel.mUserFeedBacksRequest.image1 =AppUtil.imageToBase64(this.path)
            }}catch (e:java.lang.Exception){}
            try{
                mGridImageAdapter.data[1]?.run {
                    mViewModel.mUserFeedBacksRequest.image2 =AppUtil.imageToBase64(this.path)
                }
            }catch (e:java.lang.Exception){}

            try{
                mGridImageAdapter.data[2]?.run {
                    mViewModel.mUserFeedBacksRequest.image3 =AppUtil.imageToBase64(this.path)
                }
            }catch (e:java.lang.Exception){}

            try{
                mGridImageAdapter.data[3]?.run {
                    mViewModel.mUserFeedBacksRequest.image4 =AppUtil.imageToBase64(this.path)
                }
            }catch (e:java.lang.Exception){}

            mViewModel.userFeedBacks()
        }
    }


    private fun getImageCount(){
        var count = 0
        try{
            for (item in mGridImageAdapter.data){
                try{
                     if (!StringUtils.isEmpty(item.path)){
                         count++
                     }

                }catch (e:Exception){}
            }
        }catch (e:Exception){}

        imgSelectCountTv.text = "${count}/4"
     }


}